package com.fine.hair.manage.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fine.hair.comm.dto.*;
import com.fine.hair.comm.enums.ItemType;
import com.fine.hair.comm.enums.OrderStatus;
import com.fine.hair.comm.enums.RewardsPunishmentType;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.model.*;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.vo.*;
import com.fine.hair.manage.mapper.*;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>门店相关接口</p>
 *
 * @author mouseyCat
 * @date 2020/10/9 22:59
 */
@Api(tags = {"2月19日问题接口'"})
@RestController
@RequestMapping("/feb19/")
public class LiJianController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CalendarMapper calendarMapper;

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private SecUserMapper secUserMapper;

    @Autowired
    private RewardsPunishmentMapper rewardsPunishmentMapper;


    @Autowired
    private InventoryReceiveRecordMapper inventoryReceiveRecordMapper;

    @Autowired
    private InventoryPutRecordMapper inventoryPutRecordMapper;


    @ApiOperation("删除员工-把用户从员工类型改为普通给用户类型")
    @PostMapping("delStaff")
    public ApiResponse delStaff(@RequestBody DelStaffDto dto) {
        User user = userMapper.selectById(dto.getUserId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        user.setBranchId(null);
        user.setPutBranchId(null);
        userMapper.updateById(user);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("修改员工基本信息")
    @PostMapping("modifyStaffInfo")
    public ApiResponse name(@RequestBody @Validated ModifyStaffInfoDto dto) {
        User staff = userMapper.selectById(dto.getUserId());
        if (ObjectUtil.isNull(staff)) {
            throw new BusinessException("当前员工不存在");
        }
        staff.setPhoneNumber(dto.getPhone());
        staff.setNickName(dto.getName());
        staff.setSex(dto.getSex());
        staff.setBirth(dto.getBirth());
        userMapper.updateById(staff);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation(value = "从日历分组里面删除用户 ", notes = "9-a")
    @PostMapping("delUserOnCalendar")
    public ApiResponse name(@RequestBody @Validated DelUserOnCalendarDto dto) {
        User user = userMapper.selectById(dto.getUserId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        user.setLabelType(0L);
        userMapper.updateById(user);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation(value = "将客户调整到其它周期", notes = "9-e")
    @PostMapping("changeUserCalendar")
    public ApiResponse name(@RequestBody @Validated ChangeUserCalendarDto dto) {
        User user = userMapper.selectById(dto.getUserId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        Calendar calendar = calendarMapper.selectById(dto.getCalendarId());
        if (ObjectUtil.isNull(calendar)) {
            throw new BusinessException("当前周期不存在");
        }
        user.setLabelType(Long.valueOf(dto.getCalendarId()));
        userMapper.updateById(user);
        return ApiResponse.ofSuccess();
    }

    @Autowired
    private BCryptPasswordEncoder encoder;

    @ApiOperation("修改当前账号密码")
    @PostMapping("modifyPassword")
    public ApiResponse modifyPhone(@RequestBody @Validated ModifyPasswordDTO modifyPasswordDTO) {
        SecUser secUser = secUserMapper.selectById(modifyPasswordDTO.getUserId());
        if (ObjectUtil.isNull(secUser)) {
            throw new BusinessException("当前管理员不存在");
        }
        secUser.setPassword(encoder.encode(modifyPasswordDTO.getPassword()));
        secUserMapper.updateById(secUser);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("取消订单")
    @PostMapping("cancelOrder")
    public ApiResponse staffCancelOrder(@RequestBody StaffCancelOrderDto dto) {
        Order order = orderMapper.selectById(dto.getOrderId());
        if (ObjectUtil.isNull(order)) {
            throw new BusinessException("订单不存在");
        }
        if (!order.getOrderStatus().equals(OrderStatus.WILL_COMPLETE.getCode().toString())) {
            throw new BusinessException("订单状态已不可更改");
        }
        order.setOrderStatus(OrderStatus.CANCELED.getCode().toString());
        orderMapper.updateById(order);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("首页")
    @PostMapping("homePage")
    public ApiResponse<HomePageVo> homePage(@RequestBody HomePageDto dto) {
        Branch branch;
        if (ObjectUtil.isNull(dto.getBranchId())) {
            branch = branchMapper.selectRandomOne();
        } else {
            branch = branchMapper.selectByBranchName(dto.getBranchName(), dto.getBranchId());
        }
        if (ObjectUtil.isNull(branch)) {
            throw new BusinessException("当前门店不存在");
        }
        List<HomePageVoList> homePageVoList = Lists.newArrayList();
        for (int i = 0; i < 5; i++) {
            homePageVoList.add(new HomePageVoList());
        }

        // 查询业绩
        // 昨日
        List<RewardsPunishment> rewardsPunishmentList1 = rewardsPunishmentMapper.selectYesterdayBranch(branch.getId());
        // 今日
        List<RewardsPunishment> rewardsPunishmentList2 = rewardsPunishmentMapper.selectTodayBranch(branch.getId());
        // 上个月
        List<RewardsPunishment> rewardsPunishmentList3 = rewardsPunishmentMapper.selectLastMonthBranch(branch.getId());
        // 当年
        List<RewardsPunishment> rewardsPunishmentList4 = rewardsPunishmentMapper.selectThisYearBranch(branch.getId());

        if (rewardsPunishmentList1.size() > 0) {
            BigDecimal reduce1 =
                    rewardsPunishmentList1.stream().map(RewardsPunishment::getChargeAmount).reduce(BigDecimal.ZERO,
                            BigDecimal::add);
            homePageVoList.get(0).setYesterday(reduce1);

            //List<RewardsPunishment> collect2 =
            //        rewardsPunishmentList1.stream().filter(r -> r.getType().equals(RewardsPunishmentType.PROPORTION
            //        .getCode())).collect(Collectors.toList());
            //if (collect2.size() > 0) {
            //    homePageVoList.get(1).setYesterday(collect2.stream().map(RewardsPunishment::getAmount).reduce
            //    (BigDecimal.ZERO,
            //            BigDecimal::add));
            //} else {
            //    homePageVoList.get(1).setYesterday(BigDecimal.ZERO);
            //}

        } else {
            homePageVoList.get(0).setYesterday(BigDecimal.ZERO);

        }

        if (rewardsPunishmentList2.size() > 0) {
            BigDecimal reduce2 =
                    rewardsPunishmentList2.stream().map(RewardsPunishment::getChargeAmount).reduce(BigDecimal.ZERO,
                            BigDecimal::add);
            homePageVoList.get(0).setToday(reduce2);

            //List<RewardsPunishment> collect2 =
            //        rewardsPunishmentList2.stream().filter(r -> r.getType().equals(RewardsPunishmentType.PROPORTION
            //        .getCode())).collect(Collectors.toList());
            //if (collect2.size() > 0) {
            //    homePageVoList.get(1).setToday(collect2.stream().map(RewardsPunishment::getAmount).reduce
            //    (BigDecimal.ZERO,
            //            BigDecimal::add));
            //} else {
            //    homePageVoList.get(1).setToday(BigDecimal.ZERO);
            //}
        } else {
            homePageVoList.get(0).setToday(BigDecimal.ZERO);

        }

        if (rewardsPunishmentList3.size() > 0) {
            BigDecimal reduce3 =
                    rewardsPunishmentList3.stream().map(RewardsPunishment::getChargeAmount).reduce(BigDecimal.ZERO,
                            BigDecimal::add);
            homePageVoList.get(0).setLastMonth(reduce3);

            //List<RewardsPunishment> collect2 =
            //        rewardsPunishmentList3.stream().filter(r -> r.getType().equals(RewardsPunishmentType.PROPORTION
            //        .getCode())).collect(Collectors.toList());
            //if (collect2.size() > 0) {
            //    homePageVoList.get(1).setLastMonth(collect2.stream().map(RewardsPunishment::getAmount).reduce
            //    (BigDecimal.ZERO,
            //            BigDecimal::add));
            //} else {
            //    homePageVoList.get(1).setLastMonth(BigDecimal.ZERO);
            //}

        } else {
            homePageVoList.get(0).setLastMonth(BigDecimal.ZERO);
        }

        if (rewardsPunishmentList4.size() > 0) {
            BigDecimal reduce4 =
                    rewardsPunishmentList4.stream().map(RewardsPunishment::getChargeAmount).reduce(BigDecimal.ZERO,
                            BigDecimal::add);
            homePageVoList.get(0).setThisYear(reduce4);

            //List<RewardsPunishment> collect2 =
            //        rewardsPunishmentList4.stream().filter(r -> r.getType().equals(RewardsPunishmentType.PROPORTION
            //        .getCode())).collect(Collectors.toList());
            //if (collect2.size() > 0) {
            //    homePageVoList.get(1).setThisYear(collect2.stream().map(RewardsPunishment::getAmount).reduce
            //    (BigDecimal.ZERO,
            //            BigDecimal::add));
            //} else {
            //    homePageVoList.get(1).setThisYear(BigDecimal.ZERO);
            //}
        } else {
            homePageVoList.get(0).setThisYear(BigDecimal.ZERO);
        }


        // 新增会员 通过用户的创建时间来查询 新增用户 的数据
        // 昨日
        List<User> userList1 = userMapper.selectYesterdayBranch();
        // 今日
        List<User> userList2 = userMapper.selectTodayBranch();
        // 上个月
        List<User> userList3 = userMapper.selectLastMonthBranch();
        // 当年
        List<User> userList4 = userMapper.selectThisYearBranch();

        if (userList1.size() > 0) {
            homePageVoList.get(4).setYesterday(new BigDecimal(userList1.size()));
        } else {
            homePageVoList.get(4).setYesterday(BigDecimal.ZERO);
        }
        if (userList2.size() > 0) {
            homePageVoList.get(4).setToday(new BigDecimal(userList2.size()));
        } else {
            homePageVoList.get(4).setToday(BigDecimal.ZERO);
        }
        if (userList3.size() > 0) {
            homePageVoList.get(4).setLastMonth(new BigDecimal(userList3.size()));
        } else {
            homePageVoList.get(4).setLastMonth(BigDecimal.ZERO);
        }
        if (userList4.size() > 0) {
            homePageVoList.get(4).setThisYear(new BigDecimal(userList4.size()));
        } else {
            homePageVoList.get(4).setThisYear(BigDecimal.ZERO);
        }


        // 体验客 通过订单的类型《优惠调理类型》 判断就是体验客
        // 查询体验客订单 [数据做过用户去重]
        // 昨日
        List<Order> orderList1 = orderMapper.selectYesterdayBranch(branch.getId());
        // 今日
        List<Order> orderList2 = orderMapper.selectTodayBranch(branch.getId());
        // 上个月
        List<Order> orderList3 = orderMapper.selectLastMonthBranch(branch.getId());
        // 当年
        List<Order> orderList4 = orderMapper.selectThisYearBranch(branch.getId());

        // 查询消费业绩 [数据没去重]
        // 昨日
        List<Order> orderListAll1 = orderMapper.selectYesterdayBranchAll(branch.getId());
        // 今日
        List<Order> orderListAll2 = orderMapper.selectTodayBranchAll(branch.getId());
        // 上个月
        List<Order> orderListAll3 = orderMapper.selectLastMonthBranchAll(branch.getId());
        // 当年
        List<Order> orderListAll4 = orderMapper.selectThisYearBranchAll(branch.getId());

        if (orderListAll1.size() > 0) {
            homePageVoList.get(1).setYesterday(orderListAll1.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO
                    , BigDecimal::add));
        } else {
            homePageVoList.get(1).setYesterday(BigDecimal.ZERO);
        }
        if (orderListAll2.size() > 0) {
            homePageVoList.get(1).setToday(orderListAll2.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO,
                    BigDecimal::add));
        } else {
            homePageVoList.get(1).setToday(BigDecimal.ZERO);
        }
        if (orderListAll3.size() > 0) {
            homePageVoList.get(1).setLastMonth(orderListAll3.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO
                    , BigDecimal::add));
        } else {
            homePageVoList.get(1).setLastMonth(BigDecimal.ZERO);
        }
        if (orderListAll4.size() > 0) {
            homePageVoList.get(1).setThisYear(orderListAll4.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO,
                    BigDecimal::add));
        } else {
            homePageVoList.get(1).setThisYear(BigDecimal.ZERO);
        }


        if (orderList1.size() > 0) {
            List<Order> collect1 =
                    orderList1.stream().filter(o -> o.getItemType().equals(ItemType.YH.getCode().toString())).collect(Collectors.toList());
            if (collect1.size() > 0) {
                homePageVoList.get(2).setYesterday(new BigDecimal(collect1.size()));
            } else {
                homePageVoList.get(2).setYesterday(BigDecimal.ZERO);
            }

            homePageVoList.get(3).setYesterday(new BigDecimal(orderList1.size()));
        } else {
            homePageVoList.get(2).setYesterday(BigDecimal.ZERO);
            homePageVoList.get(3).setYesterday(BigDecimal.ZERO);
        }

        if (orderList2.size() > 0) {
            List<Order> collect1 =
                    orderList2.stream().filter(o -> o.getItemType().equals(ItemType.YH.getCode().toString())).collect(Collectors.toList());
            if (collect1.size() > 0) {
                homePageVoList.get(2).setToday(new BigDecimal(collect1.size()));
            } else {
                homePageVoList.get(2).setToday(BigDecimal.ZERO);
            }

            homePageVoList.get(3).setToday(new BigDecimal(orderList1.size()));

        } else {
            homePageVoList.get(2).setToday(BigDecimal.ZERO);
            homePageVoList.get(3).setToday(BigDecimal.ZERO);
        }

        if (orderList3.size() > 0) {
            List<Order> collect1 =
                    orderList3.stream().filter(o -> o.getItemType().equals(ItemType.YH.getCode().toString())).collect(Collectors.toList());
            if (collect1.size() > 0) {
                homePageVoList.get(2).setLastMonth(new BigDecimal(collect1.size()));
            } else {
                homePageVoList.get(2).setLastMonth(BigDecimal.ZERO);
            }

            homePageVoList.get(3).setLastMonth(new BigDecimal(orderList1.size()));

        } else {
            homePageVoList.get(2).setLastMonth(BigDecimal.ZERO);
            homePageVoList.get(3).setLastMonth(BigDecimal.ZERO);
        }

        if (orderList4.size() > 0) {
            List<Order> collect1 =
                    orderList4.stream().filter(o -> o.getItemType().equals(ItemType.YH.getCode().toString())).collect(Collectors.toList());
            if (collect1.size() > 0) {
                homePageVoList.get(2).setThisYear(new BigDecimal(collect1.size()));
            } else {
                homePageVoList.get(2).setThisYear(BigDecimal.ZERO);
            }

            homePageVoList.get(3).setThisYear(new BigDecimal(orderList1.size()));

        } else {
            homePageVoList.get(2).setThisYear(BigDecimal.ZERO);
            homePageVoList.get(3).setThisYear(BigDecimal.ZERO);
        }
        HomePageVo homePageVo = new HomePageVo();
        homePageVo.setBranchName(branch.getTitle());
        homePageVo.setHomePageVoList(homePageVoList);

        return ApiResponse.ofSuccess(homePageVo);
    }

    @ApiOperation("当日排业绩行榜")
    @PostMapping("todayRanking")
    public ApiResponse<TodayRankingVo> TodayRanking(@RequestBody HomePageDto dto) {
        Branch branch;
        if (ObjectUtil.isNull(dto.getBranchId())) {
            branch = branchMapper.selectRandomOne();
        } else {
            branch = branchMapper.selectByBranchName(dto.getBranchName(), dto.getBranchId());
        }
        List<Order> orderListAll2 = orderMapper.selectTodayBranchAll(branch.getId());
        List<Order> collect =
                orderListAll2.stream().filter(o -> o.getOrderStatus().equals(OrderStatus.COMPLETED.getCode().toString())).collect(Collectors.toList());

        List<String> technicianIds =
                collect.stream().distinct().map(Order::getTechnicianId).collect(Collectors.toList());

        // 去重
        if (!CollectionUtils.isEmpty(technicianIds)) {
            technicianIds = technicianIds.stream().distinct().collect(Collectors.toList());
        }
        List<ConsumeVo> ConsumeVoList = Lists.newArrayList();
        // 处理消费业绩
        for (String technicianId : technicianIds) {
            User user = userMapper.selectById(technicianId);
            if (ObjectUtil.isNull(user)) {
                throw new BusinessException("当前用户不存在");
            }
            List<Order> collect1 =
                    collect.stream().filter(o -> o.getTechnicianId().equals(technicianId)).collect(Collectors.toList());
            ConsumeVo consumeVo = new ConsumeVo();
            consumeVo.setName(user.getNickName());
            if (collect1.size() > 0) {
                consumeVo.setMoney(collect1.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
            } else {
                consumeVo.setMoney(BigDecimal.ZERO);
            }
            ConsumeVoList.add(consumeVo);
        }
        // TODO 消费业绩排序 大到小
        List<ConsumeVo> result1 =
                ConsumeVoList.stream().sorted(Comparator.comparing(ConsumeVo::getMoney).reversed()).collect(Collectors.toList());


        // 今日
        List<RewardsPunishment> rewardsPunishmentList2 = rewardsPunishmentMapper.selectTodayBranch(branch.getId());
        List<String> rewardsPunishmentUserIds =
                rewardsPunishmentList2.stream().distinct().map(RewardsPunishment::getUserId).collect(Collectors.toList());
        List<RechargeVo> rechargeVoList = Lists.newArrayList();

        for (String rewardsPunishmentUserId : rewardsPunishmentUserIds) {
            User user = userMapper.selectById(rewardsPunishmentUserId);
            if (ObjectUtil.isNull(user)) {
                throw new BusinessException("当前用户不存在");
            }
            RechargeVo rechargeVo = new RechargeVo();
            rechargeVo.setName(user.getNickName());
            List<RewardsPunishment> collect1 =
                    rewardsPunishmentList2.stream().filter(r -> r.getUserId().equals(rewardsPunishmentUserId)).collect(Collectors.toList());
            if (collect1.size() > 0) {
                rechargeVo.setMoney(collect1.stream().map(RewardsPunishment::getChargeAmount).reduce(BigDecimal.ZERO,
                        BigDecimal::add));
            } else {
                rechargeVo.setMoney(BigDecimal.ZERO);
            }
            rechargeVoList.add(rechargeVo);
        }
        // TODO 现金业绩排序 大到小
        List<RechargeVo> result2 =
                rechargeVoList.stream().sorted(Comparator.comparing(RechargeVo::getMoney).reversed()).collect(Collectors.toList());
        TodayRankingVo todayRankingVo = new TodayRankingVo();
        todayRankingVo.setBranchName(branch.getTitle());
        todayRankingVo.setConsumeVoList(result1);
        todayRankingVo.setRechargeVoList(result2);

        return ApiResponse.ofSuccess(todayRankingVo);
    }


    @ApiOperation("门店员工收入表")
    @PostMapping("financeOne")
    public ApiResponse<FinanceOneVo> financeOne(@RequestBody FinanceOneDto dto) {

        String date = LocalDateTime.now().getYear() + "-" + LocalDateTime.now().getMonthValue();

        List<FinanceVo> financeVoList = Lists.newArrayList();
        Branch branch;
        if (ObjectUtil.isNull(dto.getBranchId())) {
            branch = branchMapper.selectRandomOne();
        } else {
            branch = branchMapper.selectByBranchName(null, dto.getBranchId());
        }
        if (ObjectUtil.isNull(branch)) {
            throw new BusinessException("当前门店不存在");
        }
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getPutBranchId,
                dto.getBranchId()));
        for (User user : users) {
            FinanceVo financeVo = new FinanceVo();
            financeVo.setName(user.getNickName());
            List<Order> orders = orderMapper.selectOrderByDateAndUserIdAndBranchId(date, user.getId(),
                    String.valueOf(user.getBranchId()));
            if (orders.size() > 0) {
                financeVo.setSale(orders.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO, BigDecimal::add));

            } else {
                financeVo.setSale(BigDecimal.ZERO);
            }
            List<RewardsPunishment> rewardsPunishmentList =
                    rewardsPunishmentMapper.selectByDateAndUserId(date, user.getId());
            if (rewardsPunishmentList.size() > 0) {
                // 销售提成
                List<RewardsPunishment> collect =
                        rewardsPunishmentList.stream().filter(r -> r.getType().equals(RewardsPunishmentType.PROPORTION.getCode())).collect(Collectors.toList());
                if (collect.size() > 0) {
                    financeVo.setSaleCommission(collect.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                } else {
                    financeVo.setSaleCommission(BigDecimal.ZERO);
                }

                // 手工提成
                List<RewardsPunishment> collect2 =
                        rewardsPunishmentList.stream().filter(r -> r.getType().equals(RewardsPunishmentType.REAL_MONEY_PROPORTION.getCode())).collect(Collectors.toList());
                if (collect2.size() > 0) {
                    financeVo.setChargeAmountCommission(collect2.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                } else {
                    financeVo.setChargeAmountCommission(BigDecimal.ZERO);
                }

                // 奖励
                List<RewardsPunishment> collect3 =
                        rewardsPunishmentList.stream().filter(r -> r.getType().equals(RewardsPunishmentType.AWARD.getCode())).collect(Collectors.toList());

                if (collect3.size() > 0) {
                    financeVo.setChargeAmountCommission(collect3.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                } else {
                    financeVo.setChargeAmountCommission(BigDecimal.ZERO);
                }

                // 惩罚
                List<RewardsPunishment> collect4 =
                        rewardsPunishmentList.stream().filter(r -> r.getType().equals(RewardsPunishmentType.PUNISHMENT.getCode())).collect(Collectors.toList());

                if (collect4.size() > 0) {
                    financeVo.setChargeAmountCommission(collect4.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                } else {
                    financeVo.setChargeAmountCommission(BigDecimal.ZERO);
                }

            } else {
                financeVo.setChargeAmountCommission(BigDecimal.ZERO);
                financeVo.setPunishment(BigDecimal.ZERO);
                financeVo.setReward(BigDecimal.ZERO);
                financeVo.setSaleCommission(BigDecimal.ZERO);
            }
            financeVo.setTotal(financeVo.getSale().add(financeVo.getChargeAmountCommission()).add(financeVo.getPunishment()).add(financeVo.getReward()).add(financeVo.getSaleCommission()));
            financeVoList.add(financeVo);
        }
        FinanceOneVo financeOneVo = new FinanceOneVo();
        financeOneVo.setBranchNameAndDate(branch.getTitle() + date.split("-")[1] + "月");
        financeOneVo.setList(financeVoList);
        return ApiResponse.ofSuccess(financeOneVo);
    }


    @ApiOperation("支出统计")
    @PostMapping("expendStat")
    public ApiResponse name(@RequestBody ExpendStatDto dto) {
        ArrayList<ExpendStatVo> expendStatVoList = Lists.newArrayList();
        for (int i = 0; i < 3; i++) {
            expendStatVoList.add(new ExpendStatVo());
        }

        List<Order> orders1 = orderMapper.selectTodayBranchAll(Long.valueOf(dto.getBranchId()));
        List<Order> orders2 = orderMapper.selectThisMonthBranchAll(Long.valueOf(dto.getBranchId()));
        List<Order> orders3 = orderMapper.selectThisQuarterBranchAll(dto.getBranchId());
        List<Order> orders4 = orderMapper.selectThisYearBranchAll(Long.valueOf(dto.getBranchId()));

        if (orders1.size() > 0) {
            expendStatVoList.get(0).setToday(orders1.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO,
                    BigDecimal::add));
        }
        if (orders2.size() > 0) {
            expendStatVoList.get(0).setThisMonth(orders2.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO,
                    BigDecimal::add));
        }
        if (orders3.size() > 0) {
            expendStatVoList.get(0).setThisQuarter(orders3.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO,
                    BigDecimal::add));
        }
        if (orders4.size() > 0) {
            expendStatVoList.get(0).setThisYear(orders4.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO,
                    BigDecimal::add));
        }

        List<RewardsPunishment> rewardsPunishment1 =
                rewardsPunishmentMapper.selectTodayBranch(Long.valueOf(dto.getBranchId()));
        List<RewardsPunishment> rewardsPunishment2 =
                rewardsPunishmentMapper.selectThisMonthBranchAll(Long.valueOf(dto.getBranchId()));
        List<RewardsPunishment> rewardsPunishment3 =
                rewardsPunishmentMapper.selectThisQuarterBranchAll(dto.getBranchId());
        List<RewardsPunishment> rewardsPunishment4 =
                rewardsPunishmentMapper.selectThisYearBranch(Long.valueOf(dto.getBranchId()));

        if (rewardsPunishment1.size() > 0) {
            List<RewardsPunishment> collect =
                    rewardsPunishment1.stream().filter(r -> r.getType().equals(RewardsPunishmentType.REAL_MONEY_PROPORTION.getCode())).collect(Collectors.toList());
            if (collect.size() > 0) {
                expendStatVoList.get(1).setToday(collect.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        if (rewardsPunishment2.size() > 0) {
            List<RewardsPunishment> collect =
                    rewardsPunishment1.stream().filter(r -> r.getType().equals(RewardsPunishmentType.REAL_MONEY_PROPORTION.getCode())).collect(Collectors.toList());
            if (collect.size() > 0) {
                expendStatVoList.get(1).setThisMonth(collect.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        if (rewardsPunishment3.size() > 0) {
            List<RewardsPunishment> collect =
                    rewardsPunishment1.stream().filter(r -> r.getType().equals(RewardsPunishmentType.REAL_MONEY_PROPORTION.getCode())).collect(Collectors.toList());
            if (collect.size() > 0) {
                expendStatVoList.get(1).setThisQuarter(collect.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        if (rewardsPunishment4.size() > 0) {
            List<RewardsPunishment> collect =
                    rewardsPunishment1.stream().filter(r -> r.getType().equals(RewardsPunishmentType.REAL_MONEY_PROPORTION.getCode())).collect(Collectors.toList());
            if (collect.size() > 0) {
                expendStatVoList.get(1).setThisYear(collect.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        expendStatVoList.get(2).setToday(expendStatVoList.get(0).getToday().add(expendStatVoList.get(1).getToday()));
        expendStatVoList.get(2).setThisMonth(expendStatVoList.get(0).getThisMonth().add(expendStatVoList.get(1).getThisMonth()));
        expendStatVoList.get(2).setThisQuarter(expendStatVoList.get(0).getThisQuarter().add(expendStatVoList.get(1).getThisQuarter()));
        expendStatVoList.get(2).setThisYear(expendStatVoList.get(0).getThisYear().add(expendStatVoList.get(1).getThisYear()));

        return ApiResponse.ofSuccess(expendStatVoList);

    }


    @ApiOperation("流量统计")
    @PostMapping("flowStat")
    public ApiResponse<List<FlowStatVo>> flowStat(@RequestBody FlowStatDto dto) {
        List<FlowStatVo> flowStatVoList = Lists.newArrayList();
        int hour = 9;
        for (int i = 0; i < 6; i++) {
            Integer count = 0;
            FlowStatVo flowStatVo = new FlowStatVo();
            if (hour == 9) {
                flowStatVo.setTime("0" + hour + ":00");
            } else {
                flowStatVo.setTime(hour + ":00");
            }

            // 处理 开始时间 和 结束时间
            if (hour == 9) {
                String startTime = LocalDateTime.now().getYear() + flowStatVo.getTime();
                String endTime = LocalDateTime.now().getYear() + "12:00";
                count = orderMapper.selectFlowStat(dto.getBranchId(), startTime, endTime);

            }
            if (hour == 12) {
                String startTime = LocalDateTime.now().getYear() + flowStatVo.getTime();
                String endTime = LocalDateTime.now().getYear() + "12:00";
                count = orderMapper.selectFlowStat(dto.getBranchId(), startTime, endTime);
            }
            if (hour == 14) {
                String startTime = LocalDateTime.now().getYear() + flowStatVo.getTime();
                String endTime = LocalDateTime.now().getYear() + "14:00";
            }
            if (hour == 16) {
                String startTime = LocalDateTime.now().getYear() + flowStatVo.getTime();
                String endTime = LocalDateTime.now().getYear() + "16:00";
                count = orderMapper.selectFlowStat(dto.getBranchId(), startTime, endTime);
            }
            if (hour == 18) {
                String startTime = LocalDateTime.now().getYear() + flowStatVo.getTime();
                String endTime = LocalDateTime.now().getYear() + "18:00";
                count = orderMapper.selectFlowStat(dto.getBranchId(), startTime, endTime);
            }
            if (hour == 20) {
                String startTime = LocalDateTime.now().getYear() + flowStatVo.getTime();
                String endTime = LocalDateTime.now().getYear() + "20:00";
                count = orderMapper.selectFlowStat(dto.getBranchId(), startTime, endTime);
            }
            flowStatVo.setCount(count);

            if (i == 0) {
                hour += 3;
            } else {
                hour += 2;
            }
            flowStatVoList.add(flowStatVo);
        }
        return ApiResponse.ofSuccess(flowStatVoList);
    }

    @ApiOperation("未消耗统计")
    @PostMapping("notConsumedStat")
    public ApiResponse notConsumedStat(@RequestBody NotConsumedStatDto dto) {
        List<NotConsumedStatVo> notConsumedStatVoList = Lists.newArrayList();

        int year = LocalDateTime.now().getYear();
        int monthValue = LocalDateTime.now().getMonthValue();
        long more = 0L;
        for (int i = 1; i <= monthValue; i++) {
            String date;
            if (i < 10) {
                date = year + "-0" + i;
            } else {
                date = year + "-" + i;
            }

            List<InventoryPutRecord> list1 = inventoryPutRecordMapper.selectListByDate(date, dto.getBranchId());
            List<InventoryReceiveRecord> list2 = inventoryReceiveRecordMapper.selectListByDate(date, dto.getBranchId());
            long ru = list1.stream().map(InventoryPutRecord::getCount).count();
            long chu = list2.stream().map(InventoryReceiveRecord::getCount).count();
            NotConsumedStatVo notConsumedStatVo = new NotConsumedStatVo();
            notConsumedStatVo.setTime(i + "月");
            notConsumedStatVo.setCount(ru - chu + more);
            notConsumedStatVoList.add(notConsumedStatVo);
            more = ru - chu;
        }
        return ApiResponse.ofSuccess(notConsumedStatVoList);
    }

    @ApiOperation("各店支出")
    @PostMapping("branchExpend")
    public ApiResponse branchExpend(@RequestBody BranchExpendDto dto) {

        int year = LocalDateTime.now().getYear();
        int m = LocalDateTime.now().getMonthValue();
        int quarter = 0;
        if (m >= 1 && m <= 3) {
            quarter = 1;
        }
        if (m >= 4 && m <= 6) {
            quarter = 2;
        }
        if (m >= 7 && m <= 9) {
            quarter = 3;
        }
        if (m >= 10 && m <= 12) {
            quarter = 4;
        }
        String startOne = "";
        String endOne = "";
        String startTwo = "";
        String endTwo = "";
        String startThree = "";
        String endThree = "";
        String startFour = "";
        String endFour = "";

        String timeOne = "";
        String timeTwo = "";
        String timeThree = "";
        String timeFour = "";
        if (quarter == 1) {
            int year2 = year - 1;
            startOne = year2 + "-04-01 00:00:00";
            endOne = year2 + "-06-30 23:59:59";
            timeOne = "去年2季度";
            startTwo = year2 + "-07-01 00:00:00";
            endTwo = year2 + "-09-30 23:59:59";
            timeTwo = "去年3季度";
            startThree = year2 + "-10-01 00:00:00";
            endThree = year2 + "-12-31 23:59:59";
            timeThree = "去年4季度";
            startFour = year + "-01-01 00:00:00";
            endFour = year + "-03-31 23:59:59";
            timeFour = "今年1季度";

        }
        if (quarter == 2) {
            int year2 = year - 1;
            startOne = year2 + "07-01 00:00:00";
            endOne = year2 + "-09-30 23:59:59";
            timeOne = "去年3季度";
            startTwo = year2 + "-10-01 00:00:00";
            endTwo = year2 + "-12-31 23:59:59";
            timeTwo = "去年4季度";
            startThree = year + "-01-01 00:00:00";
            endThree = year + "-03-01 23:59:59";
            timeThree = "今年1季度";
            startFour = year + "-04-01 00:00:00";
            endFour = year + "-06-30 23:59:59";
            timeFour = "今年2季度";
        }
        if (quarter == 3) {
            int year2 = year - 1;
            startOne = year2 + "10-01 00:00:00";
            endOne = year2 + "-12-31 23:59:59";
            timeOne = "去年4季度";
            startTwo = year + "-01-01 00:00:00";
            endTwo = year + "-03-31 23:59:59";
            timeTwo = "今年1季度";
            startThree = year + "-04-01 00:00:00";
            endThree = year + "-06-30 23:59:59";
            timeThree = "今年2季度";
            startFour = year + "-07-01 00:00:00";
            endFour = year + "-09-30 23:59:59";
            timeFour = "今年3季度";
        }
        if (quarter == 4) {
            startOne = year + "01-01 00:00:00";
            endOne = year + "-03-31 23:59:59";
            timeOne = "今年1季度";
            startTwo = year + "-04-01 00:00:00";
            endTwo = year + "-06-30 23:59:59";
            timeTwo = "今年2季度";
            startThree = year + "-07-01 00:00:00";
            endThree = year + "-09-30 23:59:59";
            timeThree = "今年3季度";
            startFour = year + "-10-01 00:00:00";
            endFour = year + "-12-31 23:59:59";
            timeFour = "今年4季度";
        }

        List<InventoryReceiveRecord> list1 = inventoryReceiveRecordMapper.selectByStartAndEndTime(startOne, endOne, dto.getBranchId());
        List<InventoryReceiveRecord> list2 = inventoryReceiveRecordMapper.selectByStartAndEndTime(startTwo, endTwo, dto.getBranchId());
        List<InventoryReceiveRecord> list3 = inventoryReceiveRecordMapper.selectByStartAndEndTime(startThree, endThree, dto.getBranchId());
        List<InventoryReceiveRecord> list4 = inventoryReceiveRecordMapper.selectByStartAndEndTime(startFour, endFour, dto.getBranchId());

        List<RewardsPunishment> list11 = rewardsPunishmentMapper.selectByStartAndEndTime(startOne, endOne, dto.getBranchId());
        List<RewardsPunishment> list22 = rewardsPunishmentMapper.selectByStartAndEndTime(startTwo, endTwo, dto.getBranchId());
        List<RewardsPunishment> list33 = rewardsPunishmentMapper.selectByStartAndEndTime(startThree, endThree, dto.getBranchId());
        List<RewardsPunishment> list44 = rewardsPunishmentMapper.selectByStartAndEndTime(startFour, endFour, dto.getBranchId());

        BigDecimal moneyOne = BigDecimal.ZERO;
        BigDecimal moneyTwo = BigDecimal.ZERO;
        BigDecimal moneyThree = BigDecimal.ZERO;
        BigDecimal moneyFour = BigDecimal.ZERO;

        for (InventoryReceiveRecord inventoryReceiveRecord : list1) {
            InventoryPutRecord inventoryPutRecord = inventoryPutRecordMapper.selectOneRecord(inventoryReceiveRecord.getInventoryId());
            if (ObjectUtil.isNull(inventoryPutRecord)) {
                throw new BusinessException("当前物品没有入库记录");
            }
            moneyOne = moneyOne.add(inventoryPutRecord.getMoney().multiply(new BigDecimal(inventoryReceiveRecord.getCount())));
        }
        BigDecimal reduce1 = list11.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        moneyOne = moneyOne.add(reduce1);


        for (InventoryReceiveRecord inventoryReceiveRecord : list2) {
            InventoryPutRecord inventoryPutRecord = inventoryPutRecordMapper.selectOneRecord(inventoryReceiveRecord.getInventoryId());
            if (ObjectUtil.isNull(inventoryPutRecord)) {
                throw new BusinessException("当前物品没有入库记录");
            }
            moneyTwo = moneyTwo.add(inventoryPutRecord.getMoney().multiply(new BigDecimal(inventoryReceiveRecord.getCount())));
        }
        BigDecimal reduce2 = list22.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        moneyTwo = moneyTwo.add(reduce2);


        for (InventoryReceiveRecord inventoryReceiveRecord : list3) {
            InventoryPutRecord inventoryPutRecord = inventoryPutRecordMapper.selectOneRecord(inventoryReceiveRecord.getInventoryId());
            if (ObjectUtil.isNull(inventoryPutRecord)) {
                throw new BusinessException("当前物品没有入库记录");
            }
            moneyThree = moneyThree.add(inventoryPutRecord.getMoney().multiply(new BigDecimal(inventoryReceiveRecord.getCount())));
        }
        BigDecimal reduce3 = list33.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        moneyThree = moneyThree.add(reduce3);


        for (InventoryReceiveRecord inventoryReceiveRecord : list4) {
            InventoryPutRecord inventoryPutRecord = inventoryPutRecordMapper.selectOneRecord(inventoryReceiveRecord.getInventoryId());
            if (ObjectUtil.isNull(inventoryPutRecord)) {
                throw new BusinessException("当前物品没有入库记录");
            }
            moneyFour = moneyFour.add(inventoryPutRecord.getMoney().multiply(new BigDecimal(inventoryReceiveRecord.getCount())));
        }
        BigDecimal reduce4 = list44.stream().map(RewardsPunishment::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        moneyFour = moneyFour.add(reduce4);

        List<BranchExpendVo> branchExpendVoList = Lists.newArrayList();
        BranchExpendVo branchExpendVo1 = new BranchExpendVo();
        branchExpendVo1.setTime(timeOne);
        branchExpendVo1.setAmount(moneyOne);
        branchExpendVoList.add(branchExpendVo1);
        BranchExpendVo branchExpendVo2 = new BranchExpendVo();
        branchExpendVo2.setTime(timeTwo);
        branchExpendVo2.setAmount(moneyTwo);
        branchExpendVoList.add(branchExpendVo2);
        BranchExpendVo branchExpendVo3 = new BranchExpendVo();
        branchExpendVo3.setTime(timeThree);
        branchExpendVo3.setAmount(moneyThree);
        branchExpendVoList.add(branchExpendVo3);
        BranchExpendVo branchExpendVo4 = new BranchExpendVo();
        branchExpendVo4.setTime(timeFour);
        branchExpendVo4.setAmount(moneyFour);
        branchExpendVoList.add(branchExpendVo4);


        return ApiResponse.ofSuccess(branchExpendVoList);
    }


    @ApiOperation("收入年份")
    @PostMapping("incomeYear")
    public ApiResponse incomeYear(@RequestBody IncomeYearDto dto) {
        List<IncomeYearVo> incomeYearVoList = Lists.newArrayList();
        int year = LocalDateTime.now().getYear();

        for (int i = 1; i <= 5; i++) {
            List<Order> orderList = orderMapper.selectByYear(i, dto.getBranchId());
            IncomeYearVo incomeYearVo = new IncomeYearVo();
            incomeYearVo.setMoney(orderList.stream().map(Order::getItemPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
            incomeYearVo.setTime(year + "年");
            year--;
            incomeYearVoList.add(incomeYearVo);
        }
        return ApiResponse.ofSuccess(incomeYearVoList);
    }
    //@ApiOperation("")
    //@PostMapping("")
    //public ApiResponse name(@RequestBody Dto dto) {
    //
    //}


}
